const express = require('express')
const app = express()

const jsonwebtoken = require('jsonwebtoken')
const { expressjwt } = require('express-jwt')

// 密钥，用于加密、解密 JWT 字符串
const secret = 'ZhangZhiqi'
app.use(
  expressjwt({
    secret,
    algorithms: ['HS256']
  }).unless({
    // 以 /api/public/ 开头的接口，不需要身份认证
    path: [/^\/api\/public\//]
  })
)

/**
 * http://127.0.0.1/api/public/login
 *  ● username  admin
 *  ● password  123456
 */
app.post(
  '/api/public/login',
  express.urlencoded({ extended: false }),
  (req, res) => {
    if (req.body.username === 'admin' && req.body.password === '123456') {
      // 生成 JWT 字符串
      const payload = { username: req.body.username }
      const options = { expiresIn: '60s' }
      const token = jsonwebtoken.sign(payload, secret, options)

      res.send({ status: 0, msg: '登录成功', data: { token } })
    } else {
      res.send({ status: 1, msg: '登录失败' })
    }
  }
)

/**
 * http://127.0.0.1/api/get/username
 *
 * Header
 *  ● Authorization   Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNzE1NTY2ODk3LCJleHAiOjE3MTU1NjY5NTd9.JNlEt_ygAXGypgPUsJOKgKSVvTBSYXn8ZjPSRNIRB48
 */
app.get('/api/get/username', (req, res) => {
  // req.auth 是 express-jwt 解析出来的数据
  const username = req.auth.username
  res.send({ status: 0, msg: '成功', data: { username } })
})

/**
 * http://127.0.0.1/api/get/error
 *
 * Header
 *  ● Authorization   Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNzE1NTY2ODk3LCJleHAiOjE3MTU1NjY5NTd9.JNlEt_ygAXGypgPUsJOKgKSVvTBSYXn8ZjPSRNIRB48
 */
app.get('/api/get/error', (req, res) => {
  throw new Error('异常')
  res.send('Hello world!')
})

const errorMiddleware = (err, req, res, next) => {
  if (err.name === 'UnauthorizedError') {
    res.status(401)
  } else {
    res.status(500)
  }
  res.send()
}
app.use(errorMiddleware)

app.listen(80, () => {
  console.log('Server running at http://127.0.0.1')
})
